﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Management;
using System.Diagnostics;
using GetDriverID;

class RSACSPSample
{
    static void Main()
    {
        Stopwatch sw = new Stopwatch(); sw.Start();
        DateTime dt = SystemTime.GetInternetTime();
        Console.WriteLine("time is " + dt.ToString());


        //string machineInfo = GetMachineInfo();
        //string machineInfo = SystemTime.getInternetTime();
        //Console.WriteLine("time is " + machineInfo);
        //Console.WriteLine("sign is " + SignRSA(machineInfo));
        sw.Stop();
        Console.WriteLine("load time is " + sw.ElapsedMilliseconds);
        Console.ReadLine();

        //SetPrivateKey();
    }

    //获取数据
    //主板制造商：{0},产品：{1},主板序列号：{2},CPU序列号为：{3},硬盘序列号为：{4}。
    private static string GetMachineInfo()
    {
        StringBuilder sb = new StringBuilder();
        ManagementObjectSearcher my = new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
        foreach (ManagementObject share in my.Get())
        {
            sb.Append(share["Manufacturer"].ToString());
            sb.Append(share["Product"].ToString());
            sb.Append(share["SerialNumber"].ToString());
        }

        //得到cpu序列号 
        string strCPUNo = string.Empty;
        ManagementClass cimObject = new ManagementClass("Win32_Processor");
        ManagementObjectCollection mocHard = cimObject.GetInstances();
        foreach (ManagementObject moHard in mocHard)
        {
            strCPUNo = moHard.Properties["ProcessorId"].Value.ToString();
        }
        sb.Append(strCPUNo);

        //硬盘序列号 
        ManagementObject m_objDisk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
        sb.Append((string)m_objDisk.GetPropertyValue("VolumeSerialNumber"));
        return sb.ToString();
    }

    private static void SetPrivateKey()
    {
        string PrivateKeyPath = "Private_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xml";
        string PublicKeyPath = "Public_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xml";
        string SignPath = "Sign_" + DateTime.Now.ToString("yyyyMMddHHmmss");

        RasCrypto rsa = new RasCrypto();
        string s = rsa.GetRSAParametersData(true);
        string privateKey = rsa.PrivateKey;
        CreatetToFile(PrivateKeyPath, rsa.PrivateKey);
        CreatetToFile(PublicKeyPath, rsa.PublicKey);
        CreatetToFile(SignPath, rsa.Sign(GetMachineInfo()));
    }

    private static bool SignRSA(string data)
    {
        string PrivateKeyPath = "Private.xml";
        string path = DateTime.Now.ToString("yyyyMMddHHmmss");
        CreateFolder(path);
        string PublicKeyPath = path + "\\Kwan";
        string SignPath = path + "\\Kwans";

        RasCrypto rsa = new RasCrypto();
        rsa.PrivateKey = GetFileString(PrivateKeyPath);
        string publicKey = rsa.PublicKey;
        string signKey = rsa.Sign(data);
        CreatetToFile(PublicKeyPath, publicKey);
        CreatetToFile(SignPath, signKey);
        return rsa.Verify(data, signKey);
    }

    /// <summary>
    /// 创建私钥文件
    /// </summary>
    /// <param name="path"></param>
    /// <param name="privatekey"></param>
    public static void CreatetToFile(string path, string privatekey)
    {
        try
        {
            string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string filePath = solutionPath + path;

            FileStream privatekeyxml = new FileStream(filePath, FileMode.Create);
            StreamWriter sw = new StreamWriter(privatekeyxml);
            sw.WriteLine(privatekey);
            sw.Close();
            privatekeyxml.Close();
        }
        catch
        {
            throw;
        }
    }

    #region 创建文件夹
    /// <summary>
    /// 创建文件夹
    /// </summary>
    /// <param name="Folder">文件夹名称</param>
    /// <returns>提示信息</returns>
    public static void CreateFolder(string Folder)
    {
        string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        string path = solutionPath + Folder;
        //如果文件不存在,将创建文件
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
    }
    #endregion

    #region 获取文件字符串
    /// <summary>
    /// 获取文件字符串
    /// </summary>
    /// <param name="fileName">文件名称</param>
    /// <returns>提示信息</returns>
    public static string GetFileString(string fileName)
    {
        string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        if (solutionPath[solutionPath.Length - 1] != '\\') solutionPath = solutionPath + "\\";
        string filePath = solutionPath + fileName;
        Encoding code = Encoding.GetEncoding("utf-8");
        //如果文件不存在,将创建文件
        if (!File.Exists(filePath))
        {
            File.Create(filePath);
        }

        StreamReader sr = null;
        string strOld = "";
        try
        {
            sr = new StreamReader(filePath, code);
            strOld = sr.ReadToEnd(); // 读取文件
            sr.Close();
            return strOld;
        }
        catch
        {
            //return exp.Message;
        }
        return "";
    }
    #endregion
}
